<template>
  <div class="home-container">
    <!-- 左侧导航栏 -->
    <div class="sidebar">
      <div class="user-info">
        <el-avatar :size="60" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
        <h3>{{ username }}</h3>
        <p>欢迎使用课程系统</p>
      </div>
      <el-menu
        :default-active="activeMenu"
        class="sidebar-menu flex justify-center"
        @select="handleMenuSelect"
      >
          <el-menu-item index="schedule">
            <div class="flex items-center justify-center w-full h-full">
            <el-icon><Grid /></el-icon>
            <span>我的课表</span>
            </div>
          </el-menu-item>
          <el-menu-item index="courses">
            <div class="flex items-center justify-center w-full h-full">
            <el-icon><Calendar /></el-icon>
            <span>课程管理</span>
            </div>
          </el-menu-item>
      </el-menu>
      <div class="sidebar-footer">
        <el-button type="danger" @click="logout" size="default" style="width: 100%;">退出登录</el-button>
      </div>
    </div>
    
    <!-- 右侧内容区域 -->
    <div class="main-content">
      <div class="content-body" style="padding: 10px 10px 17px 10px !important;">
        <!-- 课表界面 -->
        <div v-if="activeMenu === 'schedule'">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="周视图" name="week">
              <div style="display: flex; justify-content: center;">
                <el-alert
                  title="Excel模板需包含：课程名、教师、地点、星期几、第几节、类型（必修/选修）"
                  type="info"
                  show-icon
                  style="  width: 100%; text-align: center;"
                />
              </div>
              <div style="display: flex; justify-content: space-between; align-items: center; margin: 10px 0 15px 0;">
            <el-upload
              :action="importUrl"
              :headers="uploadHeaders"
              :data="{ userId: userId }"
              :show-file-list="false"
              accept=".xls,.xlsx"
              :on-success="onImportSuccess"
              :on-error="onImportError"
              :before-upload="beforeUpload"
              style=""
            >
              <el-button type="primary" size="large">选择Excel文件上传</el-button>
            </el-upload>
            <el-button type="primary" size="large" @click="dialogAddVisible = true">新增课程</el-button>
          </div>
              
              <el-table :data="tableData" border style="width: 100%;">
                <template #empty>
                  <el-empty description="暂无课程" />
                </template>
                <el-table-column prop="periodLabel" label="节次/星期" width="90" align="center" header-align="center" />
                <el-table-column prop="periodTime" label="时间" width="110" align="center" header-align="center" />
                <el-table-column v-for="day in weekDays" :key="day" :label="day" align="center" header-align="center">
                  <template #default="scope">
                    <template v-if="scope.row[day] && scope.row[day].length">
                      <div v-for="(course, idx) in scope.row[day]" :key="idx"
                        :style="{
                          position: 'relative',
                          background: course.type === '必修' ? colorRequired : colorOptional,
                          borderRadius: '5px',
                          color: '#fff',
                          padding: '10px',
                          minWidth: '100px',
                          minHeight: '60px',
                          display: 'flex',
                          flexDirection: 'column',
                          justifyContent: 'center',
                          alignItems: 'center',
                          gap: '2px',
                          marginBottom: '8px', // 卡片间距
                          boxShadow: '0 2px 8px rgba(80, 60, 180, 0.18)',
                          transition: 'all 0.3s',
                          cursor: 'pointer',
                        }"
                        
                      >
                        <span :style="{
                          position: 'absolute',
                          right: '4px',
                          top: '4px',
                          background: '#fff',
                          color: course.type === '必修' ? colorRequired : colorOptional,
                          borderRadius: '5px',
                          padding: '2px 2px',
                          fontSize: '12px',
                          fontWeight: 'bold',
                          textAlign: 'center',
                          maxWidth: '20px'
                        }">{{ course.type === '必修' ?'必':'选' }}</span>
                        <div style="width: 100%; text-align: center;">{{ course.weeks || '' }}</div>
                        <div style="width: 100%; text-align: center;">{{ course.name || '' }}</div>
                        <div style="width: 100%; text-align: center;">{{ course.teacher || '' }}</div>
                        <div style="width: 100%; text-align: center;">{{ course.place || '' }}</div>
                      </div>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="日视图" name="day">
              <el-select v-model="selectedDay" placeholder="选择星期" style="margin-bottom: 16px;">
                <el-option v-for="day in weekDays" :key="day" :label="day" :value="day" />
              </el-select>
              <el-table :data="dayTableData" border style="width: 100%;">
                <el-table-column prop="period" label="节次" width="80" align="center" header-align="center" />
                <el-table-column prop="periodTime" label="时间" width="110" align="center" header-align="center" />
                <el-table-column prop="name" label="课程" align="center" header-align="center" />
                <el-table-column prop="place" label="地点" align="center" header-align="center" />
                <el-table-column prop="teacher" label="教师" align="center" header-align="center" />
                <el-table-column prop="type" label="类型" align="center" header-align="center">
                  <template #default="scope">
                    <div :style="{
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                      width: '100%',
                      height: '100%',
                    }">
                      <span :style="{
                        display: 'inline-block',
                        minWidth: '40px',
                        padding: '2px 12px',
                        backgroundColor: scope.row.type === '必修' ? colorRequired : colorOptional,
                        color: '#fff',
                        borderRadius: '12px',
                        fontWeight: 'bold',
                        textAlign: 'center',
                      }">{{ scope.row.type }}</span>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
          
        </div>

        <!-- 课程管理界面 -->
        <div v-if="activeMenu === 'courses'">

          <div style="display: flex; justify-content: center;">
            <el-alert
              title="Excel模板需包含：课程名、教师、地点、星期几、第几节、类型（必修/选修）"
              type="info"
              show-icon
              style="  width: 100%; text-align: center; margin-left: 25px; margin-right: 50px;"
            />
          </div>
          <div style="display: flex; justify-content: space-between; align-items: center; margin: 10px 50px 10px 25px;">
            <el-upload
              :action="importUrl"
              :headers="uploadHeaders"
              :data="{ userId: userId }"
              :show-file-list="false"
              accept=".xls,.xlsx"
              :on-success="onImportSuccess"
              :on-error="onImportError"
              :before-upload="beforeUpload"
              style=""
            >
              <el-button type="primary" size="large">选择Excel文件上传</el-button>
            </el-upload>
            <el-button type="primary" size="large" @click="dialogAddVisible = true">新增课程</el-button>
          </div>
          
          <el-table :data="sortedCourseList" style="width: 100%; " v-loading="tableLoading">
            <el-table-column prop="name" label="课程名"/>
            <el-table-column prop="teacher" label="教师" />
            <el-table-column prop="place" label="地点" />
            <el-table-column prop="weekDay" label="星期" />
            <el-table-column prop="period" label="节次" />
            <el-table-column prop="type" label="类型" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button size="small" type="primary" @click="handleEditCourse(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteCourse(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-if="sortedCourseList.length === 0" description="暂无课程" />
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="dialogAddVisible" title="新增课程" width="400px" >
    <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="80px">
      <el-form-item label="课程名" prop="name">
        <el-input v-model="addForm.name" />
      </el-form-item>
      <el-form-item label="教师" prop="teacher">
        <el-input v-model="addForm.teacher" />
      </el-form-item>
      <el-form-item label="地点" prop="place">
        <el-input v-model="addForm.place" />
      </el-form-item>
      <el-form-item label="星期几" prop="weekDay">
        <el-select v-model="addForm.weekDay" placeholder="请选择">
          <el-option v-for="(d, i) in weekDays" :key="i" :label="d" :value="d" />
        </el-select>
      </el-form-item>
      <el-form-item label="节次" prop="period">
        <el-input-number v-model="addForm.period" :min="1" :max="12" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="addForm.type" placeholder="请选择">
          <el-option label="必修" value="必修" />
          <el-option label="选修" value="选修" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogAddVisible = false">取消</el-button>
      <el-button type="primary" @click="handleAddCourse">确定</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="editDialogVisible" title="编辑课程" width="400px">
    <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="80px">
      <el-form-item label="课程名" prop="name">
        <el-input v-model="editForm.name" />
      </el-form-item>
      <el-form-item label="教师" prop="teacher">
        <el-input v-model="editForm.teacher" />
      </el-form-item>
      <el-form-item label="地点" prop="place">
        <el-input v-model="editForm.place" />
      </el-form-item>
      <el-form-item label="星期几" prop="weekDay">
        <el-select v-model="editForm.weekDay" placeholder="请选择">
          <el-option v-for="(d, i) in weekDays" :key="i" :label="d" :value="d" />
        </el-select>
      </el-form-item>
      <el-form-item label="节次" prop="period">
        <el-input-number v-model="editForm.period" :min="1" :max="12" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="editForm.type" placeholder="请选择">
          <el-option label="必修" value="必修" />
          <el-option label="选修" value="选修" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleUpdateCourse">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Calendar, Grid, User } from '@element-plus/icons-vue'
import axios from '../axios'

const router = useRouter()
const username = ref('')
const activeMenu = ref('schedule') // 默认显示课表
const activeTab = ref('week')
const selectedDay = ref('周一')
const courses = ref([])
const courseList = ref([])
const userId = localStorage.getItem('userId')
const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
const colorRequired = ref('#E6A23C')
const colorOptional = ref('#67C23A')

// 课程排序函数
const sortCourses = (courses) => {
  return courses.sort((a, b) => {
    // 首先按星期排序
    const dayA = weekDays.indexOf(a.weekDay)
    const dayB = weekDays.indexOf(b.weekDay)
    if (dayA !== dayB) {
      return dayA - dayB
    }
    // 然后按节次排序
    return Number(a.period) - Number(b.period)
  })
}

// 课程管理相关
const form = ref({
  name: '',
  teacher: '',
  place: '',
  weekDay: '',
  period: 1,
  type: ''
})
const loading = ref(false)
const tableLoading = ref(false)
const courseForm = ref(null)
const rules = {
  name: [{ required: true, message: '请输入课程名', trigger: 'blur' }],
  teacher: [{ required: true, message: '请输入教师', trigger: 'blur' }],
  place: [{ required: true, message: '请输入地点', trigger: 'blur' }],
  weekDay: [{ required: true, message: '请选择星期', trigger: 'change' }],
  period: [{ required: true, message: '请输入节次', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }]
}

const importUrl = '/api/course/import'
const uploadHeaders = {}

const dialogAddVisible = ref(false)
const addForm = ref({ name: '', teacher: '', place: '', weekDay: '', period: 1, type: '' })
const addFormRef = ref(null)

const editDialogVisible = ref(false)
const editForm = ref({ id: '', name: '', teacher: '', place: '', weekDay: '', period: 1, type: '' })
const editFormRef = ref(null)

// 排序后的课程列表
const sortedCourseList = computed(() => {
  // 先排序再去重
  const sorted = sortCourses([...courseList.value]);
  const unique = [];
  const seen = new Set();
  for (const c of sorted) {
    const key = `${c.name}__${c.teacher}__${c.place}__${c.type}__${c.period}`;
    if (!seen.has(key)) {
      seen.add(key);
      unique.push(c);
    }
  }
  return unique;
})

onMounted(() => {
  username.value = localStorage.getItem('username') || '用户'
  if (!userId) {
    ElMessage.warning('请先登录')
    router.push('/login')
  } else {
    loadCourses()
  }
})

const handleMenuSelect = (index) => {
  activeMenu.value = index
  if (index === 'schedule') {
    loadCourses()
  } else if (index === 'courses') {
    loadCourseList()
  }
}

const loadCourses = async (forceRefresh = false) => {
  try {
    const timestamp = forceRefresh ? `?t=${Date.now()}` : ''
    const res = await axios.get(`/api/course/list/${userId}${timestamp}`, {
      headers: {
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache'
      }
    })
    courses.value = res.data || []
  } catch (e) {
    ElMessage.error('加载课程失败')
  }
}

const loadCourseList = async (forceRefresh = false) => {
  tableLoading.value = true
  try {
    const timestamp = forceRefresh ? `?t=${Date.now()}` : ''
    const res = await axios.get(`/api/course/list/${userId}${timestamp}`, {
      headers: {
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache'
      }
    })
    courseList.value = res.data || []
  } catch (e) {
    ElMessage.error('加载课程失败')
  } finally {
    tableLoading.value = false
  }
}

// 课程管理功能
const onAdd = () => {
  courseForm.value.validate(async valid => {
    if (!valid) return
    loading.value = true
    try {
      const res = await axios.post('/api/course/add', {
        userId,
        name: form.value.name,
        teacher: form.value.teacher,
        place: form.value.place,
        weekDay: form.value.weekDay,
        period: form.value.period,
        type: form.value.type
      })
      if (res.data && res.data.includes('成功')) {
        ElMessage.success('添加成功')
        loadCourseList()
        loadCourses() // 同时刷新课表
        courseForm.value.resetFields()
      } else {
        ElMessage.error(res.data || '添加失败')
      }
    } catch (e) {
      ElMessage.error('网络错误')
    } finally {
      loading.value = false
    }
  })
}

const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件')
  }
  return isExcel
}

const onImportSuccess = (response) => {
  if (typeof response === 'string' && response.includes('成功')) {
    ElMessage.success('导入成功')
    loadCourseList()
    loadCourses() // 同时刷新课表
    localStorage.setItem('username', response.data.username)
  } else {
    ElMessage.error(response || '导入失败')
  }
}

const onImportError = () => {
  ElMessage.error('文件上传失败')
}

// 构建周视图表格数据
const periodLabels = ['第1节', '第2节', '第3节', '第4节', '第5节', '第6节', '第7节', '第8节', '第9节', '第10节']
const periodTimes = ['08:00~08:45', '08:55~09:40', '10:10~10:55', '11:05~11:50', '14:30~15:15', '15:25~16:10', '16:40~17:25', '17:35~18:20', '19:10~19:55', '20:05~20:50']
const periods = Array.from({ length: 10 }, (_, i) => i + 1)
const tableData = computed(() => {
  return periods.map((period, idx) => {
    const row = { period, periodLabel: periodLabels[idx] || '', periodTime: periodTimes[idx] || '' };
    weekDays.forEach(day => {
      // 找出该时间段所有课程
      const coursesInCell = courses.value.filter(
        c => c.weekDay === day && Number(c.period) === period
      );
      // 去重：课程名+教师+地点+类型+节次为唯一key
      const uniqueCourses = [];
      const seen = new Set();
      for (const c of coursesInCell) {
        const key = `${c.name}__${c.teacher}__${c.place}__${c.type}__${c.period}`;
        if (!seen.has(key)) {
          seen.add(key);
          uniqueCourses.push(c);
        }
      }
      row[day] = uniqueCourses;
    });
    return row;
  });
});

// 构建日视图表格数据
const dayTableData = computed(() => {
  // 先筛选再去重
  const filtered = courses.value
    .filter(c => c.weekDay === selectedDay.value)
    .sort((a, b) => Number(a.period) - Number(b.period));
  const unique = [];
  const seen = new Set();
  for (const c of filtered) {
    const key = `${c.name}__${c.teacher}__${c.place}__${c.type}__${c.period}`;
    if (!seen.has(key)) {
      seen.add(key);
      unique.push({
        ...c,
        periodTime: periodTimes[Number(c.period) - 1] || ''
      });
    }
  }
  return unique;
});

const logout = () => {
  localStorage.removeItem('userId')
  localStorage.removeItem('username')
  router.push('/login')
}

const handleAddCourse = () => {
  addFormRef.value.validate(async valid => {
    if (!valid) return
    try {
      const res = await axios.post('/api/course/add', {
        userId,
        name: addForm.value.name,
        teacher: addForm.value.teacher,
        place: addForm.value.place,
        weekDay: addForm.value.weekDay,
        period: addForm.value.period,
        type: addForm.value.type
      })
      if (res.data && res.data.includes('成功')) {
        ElMessage.success('添加成功')
        dialogAddVisible.value = false
        addForm.value = { name: '', teacher: '', place: '', weekDay: '', period: 1, type: '' }
        await loadCourseList(true) // 强制刷新
        await loadCourses(true) // 强制刷新
      } else if (res.data && res.data.includes('已存在')) {
        ElMessage.warning('课程已存在')
      } else {
        ElMessage.error(res.data || '添加失败')
      }
    } catch (e) {
      ElMessage.error('网络错误')
    }
  })
}

const handleEditCourse = (course) => {
  editForm.value = { ...course }
  editDialogVisible.value = true
}

const handleUpdateCourse = () => {
  editFormRef.value.validate(async valid => {
    if (!valid) return
    try {
      const res = await axios.post('/api/course/update', {
        userId,
        id: editForm.value.id,
        name: editForm.value.name,
        teacher: editForm.value.teacher,
        place: editForm.value.place,
        weekDay: editForm.value.weekDay,
        period: editForm.value.period,
        type: editForm.value.type
      })
      if (res.data && res.data.includes('成功')) {
        ElMessage.success('更新成功')
        editDialogVisible.value = false
        await loadCourseList(true)
        await loadCourses(true)
      } else {
        ElMessage.error(res.data || '更新失败')
      }
    } catch (e) {
      ElMessage.error('网络错误')
    }
  })
}

const handleDeleteCourse = (course) => {
  ElMessageBox.confirm(
    `确定要删除课程「${course.name}」吗？`,
    '删除确认',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const res = await axios.post('/api/course/delete', {
        userId,
        id: course.id
      })
      if (res.data && res.data.includes('成功')) {
        ElMessage.success('删除成功')
        await loadCourseList(true)
        await loadCourses(true)
      } else {
        ElMessage.error(res.data || '删除失败')
      }
    } catch (e) {
      ElMessage.error('网络错误')
    }
  }).catch(() => {})
}
</script>

<style scoped>
.home-container {
  display: flex;
  height: 100vh;
  background: #f5f7fa;
}

.sidebar {
  width: 200px;
  background: #409eff;
  box-shadow: 2px 0 8px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
  height: 100%;
}

.user-info {
  padding: 20px;
  text-align: center;
  /* border-bottom: 1px solid #f0f0f0; */
}

.user-info h3 {
  margin: 10px 0 5px 0;
  font-size: 16px;
  color: #333;
}

.user-info p {
  margin: 0;
  font-size: 14px;
  color: #fff;
}

.sidebar-menu {
  flex: 1;
  border: none;
  background: #409eff;
}

.sidebar-footer {
  padding: 20px;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.content-header) {
  height: 60px;
  padding: 20px 10px !important;
  border-bottom: 1px solid #f0f0f0;
}

.content-header h2 {
  margin: 0;
  font-size: 35px;
  color: #333;
}

:deep(.content-body) {
  flex: 1;
  padding: 10px 10px 18px 10px !important;
  overflow-y: auto;
}

/* 备用方案：使用更具体的选择器 */
/* .home-container .main-content :deep(.content-body) {
  padding: 10px 10px 17px 10px !important;
} */

.schedule-controls {
  margin-bottom: 20px;
}

/* 让el-table内容居中，周视图行高自适应 */
:deep(.el-table th), :deep(.el-table td) {
  text-align: center !important;
  vertical-align: middle !important;
}

:deep(.el-table .el-tag) {
  white-space: normal !important;
  word-break: break-all !important;
  line-height: 1.5 !important;
  padding: 8px 4px !important;
  display: inline-block !important;
}
:deep(.el-tabs__nav) {
  margin-bottom: 6px !important;
}
:deep(.el-tabs__nav-wrap::after) {
  display: none !important;
}
:deep(.el-tabs__header) {
  margin-bottom: 0px !important;
}
/* :deep(.el-alert) {
  margin-left: 25px !important;
  margin-right: 50px !important;
} */

/* 移除按钮点击后的黑色边框 */
:deep(.el-button:focus,.el-dialog__headerbtn:focus) {
  outline: none !important;
  /* border-color: transparent !important; */
}

:deep(.el-button:focus-visible,.el-dialog__headerbtn:focus-visible) {
  outline: none !important;
  /* border-color: transparent !important; */
}

:deep(.el-menu-item) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  padding: 0 !important;
  background: #409eff !important;
  color: #fff !important;
  font-weight: normal;
  border-left: 4px solid transparent;
  transition: background 0.3s, color 0.3s, border-left 0.3s;
}
:deep(.el-menu-item:hover) {
  background: #2176c7 !important;
  color: #fff !important;
}
:deep(.el-menu-item.is-active) {
  background: #2176c7 !important;
  color: #fff !important;
  border-left: 4px solid #fff !important;
  font-weight: bold !important;
}

</style>